package com.testing.vip14login.controller;

import com.testing.vip14login.model.Result;
import com.testing.vip14login.model.User;
import com.testing.vip14login.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @Classname UserController
 * @Description 类型说明
 * @Date 2023/9/28 21:59
 * @Created by 特斯汀Roy
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService userService;


    @PostMapping("/json")
    public Result login(@RequestBody User loginUser){
        return  userService.login(loginUser.getUsername(),loginUser.getPassword());
    }

    @PostMapping
    public Result login(@RequestParam String username, @RequestParam String password
            , HttpServletRequest request, HttpServletResponse response){
        //判断是否有用户登录了
        //生命周期，表示session能保持多久
        request.getSession().setMaxInactiveInterval(120);
        String sessionId = request.getSession().getId();
        System.out.println("------------------------本次访问的sessionId是"+sessionId);
        Object username1 = request.getSession().getAttribute("username");
        System.out.println("当前session中存储的username属性值是"+username1);
        if(username1!=null){
            return new Result(400,"已经有用户登录了","不能再次登录");
        }
        //判断登录逻辑
        Result login = userService.login(username, password);
        //返回一个cookie给客户端，让浏览器关闭之后，依然能够保持登录状态。
        if(login.getCode().equals(200)){
            //如果登录成功，存储用户名到session
            request.getSession().setAttribute("username",username);
            //向客户端返回cookie，用同名的JSESSIONID覆盖
            Cookie jSessionId=new Cookie("JSESSIONID",sessionId);
            //建议设置成跟session相同的时长。
            jSessionId.setMaxAge(120);
            //修改生命周期，不再是session内有效。
            response.addCookie(jSessionId);
        }
        return login;
    }

    /**
     * 通过用户名查询用户信息
     * @param request  请求的信息
     * @return
     */
    @GetMapping
    public Result getUser(HttpServletRequest request){
        //获取会话
        HttpSession session = request.getSession();
        System.out.println("获取会话的内容是"+session);
        String username = session.getAttribute("username").toString();
        //通过session中存储的username查询用户信息。
        return userService.getUserInfo(username);
    }

    @GetMapping("/logout")
    public Result logOut(HttpServletRequest request){
        //让session失效，从而实现登出注销。
        request.getSession().invalidate();
        return Result.success("已经退出登录","不管有没有用户");
    }

}
